package com.qk.management.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.CURDEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Dept;
import com.qk.entity.User;
import com.qk.management.mapper.DeptMapper;
import com.qk.management.service.DeptService;
import com.qk.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMappper;

    @Autowired
    private UserService userService;


    @Override
    public List<Dept> getAllDepts() {
        return deptMappper.select();
    }

    @Override
    public Integer updateDept(Integer id,String name,Integer status) {
        Dept deptById = getDeptById(id);

        if (deptById == null)
            return 0;

        deptById.setName(name);
        if (status != null)
            deptById.setStatus(status);
        deptById.setUpdateTime(LocalDateTime.now());

        deptMappper.update(deptById);
        return 1;
    }


    @Override
    public Dept getDeptById(Integer id) {
        return deptMappper.getDeptById(id);
    }

    @Override
    public void deleteDept(Integer id) {

        List<User> users = userService.getUserByDeptId(id);
        if (users != null && users.size() > 0)
            CommonException.throwCommonException(CURDEnum.DELETE_ERROR);
        deptMappper.delete(id);
    }


    /*sql优化：将计算放在代码中，不要将逻辑处理放在sql语句中，会严重影响性能*/
    @Override
    public PageResult<Dept> page(String name, Integer status, Integer page, Integer pageSize) {

        //1 开启分页查询 传统分页使用方式（土）
        PageHelper.startPage(page, pageSize);
        //2 执行查询
        List<Dept> list = deptMappper.list(name, status);
        //3.数据封装
        // 条件查询列表强转为Page类型
        Page<Dept> rs =  (Page<Dept>) list;
        // 数据封装
        return PageResult.<Dept>builder()
                .total(rs.getTotal())
                .rows(rs.getResult())
                .build();
    }




    @Override
    public void addDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMappper.insert(dept);
    }
}